/**
 * 增加菜品
 */

//引入Q模块
var Q = require('q');
//引入fileSystem模块
var fs = require('fs');
//引入公共函数
var util = require('../../util');

//add入口函数
var index = function(getData, postData, config, _redis, db) {
	var deferred = Q.defer();
	console.log('取得的删除菜单foodId' + postData.foodId);
	db.select('foodMenu').then(function(foodMenu) {
		if(foodMenu.length == 0) {
			//删除对应foodId的项
			return db.remove('foodMenu', {foodId: postData.foodId});
		}
		for(var i = 0;i < foodMenu.length;i++) {
			if(foodMenu[i].foodId == postData.foodId) {
				var foodPhotoPath = config.uploadPath + '/' + postData.storeId + '/' + postData.foodPhotoFolder + '/' + foodMenu[i].foodPhoto;
				util.fsExists(foodPhotoPath).then(function() {
					console.log('将删除文件' + foodPhotoPath);
					fs.unlink(foodPhotoPath, function(err) {
						if(err) {
							console.log('删除失败');
						}
						else {
							console.log('删除成功');
						}
						//删除对应foodId的项
						return db.remove('foodMenu', {foodId: postData.foodId});
					});
				}, function() {
					//删除对应foodId的项
					return db.remove('foodMenu', {foodId: postData.foodId});
				});
			}
			else if(i == foodMenu.length - 1) {
				//删除对应foodId的项
				deferred.resolve(1);
				return deferred.promise;
			}
		}
	}, function() {
		deferred.reject('-0063');
	}).then(function(){
		//删除菜品成功
		deferred.resolve(1);
	},function(){
		//删除菜品失败
		deferred.reject('-0064');
	});
	return deferred.promise;	
}
//暴露接口
module.exports = {
	index: index
};

